<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/30
 * Time: 10:22
 */

namespace common\components\ActionsComponents;

use common\components\OSS\AliOSS;


/**
 * 上传独立操作
 * Class UploadAction
 * @package common\components\ActionsComponents
 */
class UploadOssSignAction extends CommonAction
{
    public $message = 'success';

    public $upload_dir;

    public $expire = 30;

    public $callback;

    public $callback_params;

    //上传文件名key
    public $filename = '';

    public $uploadAfter;

    public function run()
    {
        $controller = $this->controller;

        if ( $this->callback instanceof \Closure ) {
            $callback = $this->callback;
            $this->callback = $callback();
        }

        if ( $this->callback_params instanceof \Closure ) {
            $callback_params = $this->callback_params;
            $this->callback_params = $callback_params();
        }

        $aliOss = new AliOSS();
        $ret = $aliOss->signature(
            trim($this->upload_dir, "/"),
            $this->expire,
            $this->callback,
            $this->callback_params
        );

        $sourceUrl = AliOSS::getSourceUrl(rtrim($this->upload_dir, '/') . '/' . trim($this->filename, '/'));
        if ( $this->uploadAfter ) {
            $uploadAfter = $this->uploadAfter;
            $uploadAfter($sourceUrl);
        }

        return $controller->jsonResponse(
            $controller::RESPONSE_SUCCESS,
            $this->message,[
                'result' => $ret,
                'url' => $sourceUrl
            ]
        );
    }
}